angular.module('charity.media')
    .controller('mediaCtr', ['$scope', '$filter', '$mediaService', '$routeParams', '$uibModal','logger',
    function ($scope, $filter, $mediaService, $routeParams,$uibModal,logger) {
        $scope.stores = [];
        $scope.searchKeywords = '';
        $scope.filteredStores = [];
        $scope.row = '', $scope.articleType = $routeParams.type;

        $scope.select = function (page) {
            var end, start;
            start = (page - 1) * $scope.numPerPage;
            end = start + $scope.numPerPage;
            return $scope.currentPageStores = $scope.filteredStores.slice(start, end);
        };

        $scope.onFilterChange = function () {
            $scope.select(1);
            $scope.currentPage = 1;
            return $scope.row = '';
        };

        $scope.onNumPerPageChange = function () {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.onOrderChange = function () {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.search = function () {
            $mediaService.queryReport().then(function (datas) {
                $scope.stores = datas.data;
                $scope.filteredStores = $filter('filter')($scope.stores, $scope.searchKeywords);
                return $scope.onFilterChange();
            });
        };

        $scope.order = function (rowName) {
            if ($scope.row === rowName) {
                return;
            }
            $scope.row = rowName;
            $scope.filteredStores = $filter('orderBy')($scope.stores, rowName);
            return $scope.onOrderChange();
        };
        $scope.numPerPageOpt = [3, 5, 10, 20];
        $scope.numPerPage = $scope.numPerPageOpt[2];
        $scope.currentPage = 1;
        $scope.currentPageStores = [];

        $scope.open = function(article){
            $scope.article = article;
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'myModalContent.html',
                controller: 'DeleteConfirmCtrl',
                resolve: {
                    data: function () {
                        return $scope.article
                    }
                }
            });

            modalInstance.result.then(function (article) {
                $mediaService.deleteById(article.id).then(function(results){
                    if(results.data && results.data.message){
                        logger.log(results.data.message);
                    }
                    //刷新页面
                    $scope.search();
                })
            }, function (error) {
                debugger;
            });
        };


        var init = function () {
            $scope.search();
            return $scope.select($scope.currentPage);
        };
        init();
    }])

    .controller('editMediaCtrl', ['$scope', '$mediaService', '$routeParams', 'logger', 'cfpLoadingBar', 
    function ($scope, $mediaService, $routeParams, logger, cfpLoadingBar) {
        $scope.statusOptions = [{
            id: 0,
            label: '草稿'
        }, {
            id: 1,
            label: '发布'
        }];

        $scope.typeOptions = [{
            id:10,
            label:'机构动态'   
        },{
            id:11,
            label:'项目动态'
        },{ 
            id:12,
            label:'行业动态'
        },{
            id:9,
            label:'视频'
        }]

        if (parseInt($routeParams.id) > 0) {  // 编辑
            $mediaService.query({
                articleId: $routeParams.id
            }).then(function (datas) {
                $scope.post = datas.data[0] ? datas.data[0] : {status: 0, article_type: 10};
                $scope.editor = $mediaService.getArticleEditor('editor-trigger');
                $scope.editor.$txt.html($scope.post.content);
            });
        } else {    // 新增
            if ($routeParams.id == 'video') {
                $scope.post = {status: 0, article_type: 9};
            } else {
                $scope.post = {status: 0, article_type: 10};
            }
            $scope.editor = $mediaService.getArticleEditor('editor-trigger');
            $scope.editor.$txt.html($scope.post.content);
        }

        $scope.savePost = function () {
            if ($scope.editor){
                $scope.post.content = $scope.editor.$txt.html();
            }
            if ($scope.post.id) {
                console.log('update article..');
                $mediaService.update($scope.post).then(function () {
                    logger.logSuccess('保存成功');
                }, function (error) {
                    console.log(error);
                    logger.logError('保存失败');
                });
            } else {
                console.log('new article..');
                $mediaService.save($scope.post).then(function (data) {
                    $scope.post.id = data.data.insertId;
                    logger.logSuccess('保存成功');
                }, function (error) {
                    console.log(error);
                    logger.logError('保存失败');
                });
            }

        };

        //内容图片处理
        $scope.iconFile;
        var handleIconFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];
            if (file) {
                $scope.iconFile = file;
                var reader = new FileReader();
                reader.onload = function (evt) {
                    $scope.$apply(function ($scope) {
                        $scope.selectIcon = evt.target.result;
                        $scope.post.cover_url = evt.target.result;
                    });
                };
                reader.readAsDataURL(file);
                $scope.uploadIcon();
            }
            else {
                $scope.$apply(function ($scope) {
                    $scope.iconFile = null;
                    $scope.selectIcon = null;
                });

            }
        };
        angular.element(document.querySelector('#iconFileInput')).on('change', handleIconFileSelect);

        $scope.uploadIcon = function () {
            //赋值为null，使上传按钮禁用，避免多次点击
            $scope.selectIcon = null;
            cfpLoadingBar.start();
            var avFile = new AV.File($scope.iconFile.name, $scope.iconFile);
            avFile.save().then(function () {
                console.log(avFile.url());
                // $scope.$apply(function ($scope) {
                //     $scope.post.cover_url = avFile.url();
                // });
                $scope.post.cover_url = avFile.url();
                cfpLoadingBar.complete();
                logger.logSuccess("上传成功");
            }, function (error) {
                alert('上传失败:' + error.message);
                cfpLoadingBar.complete();
                logger.logError("上传失败");
            });
        }

    }])
    .controller('DeleteConfirmCtrl', ['$scope', '$uibModalInstance', 'article', 
    function ($scope,$uibModalInstance, article) {
        $scope.article = article;
        $scope.ok = function() {    
            $uibModalInstance.close( $scope.article );
        };

        $scope.cancel = function() {
            $uibModalInstance.dismiss("cancel");
        };

    }]);